<!--
 * @Author: bb 1303338576@qq.com
 * @Date: 2022-09-06 15:31:05
 * @LastEditors: bb 1303338576@qq.com
 * @LastEditTime: 2022-09-08 20:30:21
 * @FilePath: \undefinedc:\Users\陈润彬\Desktop\代码题2静态页面结构.html
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div style="margin-bottom: 15px;">
        <form class="info" autocomplete="off">
            <input type="text" name="username" placeholder="请输入姓名">
            <input type="text" name="age" placeholder="请输入性别">
            <input type="text" name="sex" placeholder="请输入年龄">
            <input type="submit" value="提交" name="btn">
        </form>
    </div>
    <table border="1" width="540">
        <thead>
            <tr>
                <td>姓名</td>
                <td>性别</td>
                <td>年龄</td>
                <td>操作</td>
            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>
    <script>
        const data = localStorage.getItem('user-data')
        const arr = data ? JSON.parse(data) : []
        const tbody = document.querySelector('tbody')

        //渲染函数
        function render() {
            const trArr = arr.map(function (item, i) {
                console.log(item);
                return `
                <tr>
                <td>${item.username}</td>
                <td>${item.age}</td>
                <td>${item.sex}</td>
                <td><a href="javascript:" data-id=${i}>删除</a></td>
            </tr>
             `
            })
            tbody.innerHTML = trArr.join('')
        }
        render()

        //获取表单，添加表单提交事件
        const info = document.querySelector('.info')
        const items = info.querySelectorAll('[name]')
        console.log(info);
        info.addEventListener('submit', function (e) {
            e.preventDefault()
            const obj = {}
            console.log(1);
            for (let i = 0; i < items.length; i++) {
                const item = items[i]
                if (items[i].value.trim() === '') {
                    return alert('输入内容不能为空')
                }
                obj[item.name] = item.value
            }
            arr.push(obj)
            localStorage.setItem('user-data', JSON.stringify(arr))
            render()
            this.reset()
        })
        tbody.addEventListener('click', function (e) {
            if (e.target.tagName === 'A') {
                arr.splice(e.target.dataset.id, 1)
                localStorage.setItem('user-data', JSON.stringify(arr))
                render()
            }
        })
    </script>
</body>

</html>